{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The Travelling Salesman problem (TSP) is a well-known problem in computer science. Roughly speaking, it refers to a salesperson who must deliver packages in cities that are modelled through a weighted graph, and the objective is to find the optimal route such that the total distance travelled is minimized.\n",
    "\n",
    "This problem is known for its complexity and for the fact that it is a NP-hard problem, which means that there is no polynomial-time solution (assuming P != NP).\n",
    "\n",
    "The problem we must solve is, in fact, a specific variant of the TSP, called Vehicle Routing Problem (VRP) which is different from the TSP inasmuch as there are now multiple salespeople (couriers). We will, in addition, add following constraints:\n",
    "\n",
    "- Each courier has a limited space he/she can carry\n",
    "\n",
    "- New orders may appear during the trips, so the \n",
    "\n",
    "- Order may have time-constrained pickup/delivery times: if it can't be picked up/delivered by some time, it's no use.\n",
    "\n",
    "I can assume I'm given:\n",
    "\n",
    "- A reliable estimate of the time it will take a courier to go from point A to point B\n",
    "\n",
    "- The capacity each courier can carry at any one time (in litres) and the volume of each package.\n",
    "\n",
    "Other things I can assume\n",
    "\n",
    "- Couriers may deny the order\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Supposing we have to develop a quick solution just to start off with, **without looking at how other people have solved this**, here's what I would propose:\n",
    "\n",
    "> These are not optimal solutions. They're just initial solutions that gets the job done quickly.\n",
    "\n",
    "Our problem can be approached like this:\n",
    "\n",
    "> Given a steady stream of new packages, how to I assign couriers to a) pick up the packages and b) deliver those packages, so as to minimize the total amount of time/distance travelled by the couriers and, possibly, also minimize the amount of time they are waiting.\n",
    "\n",
    "- I would split the city into a number of non-overlapping **areas** and suppose I have some number of couriers either active or waiting in each of those areas. \n",
    "\n",
    "### Assumptions\n",
    "\n",
    " - Let's assume that orders within those areas are considered to be \"nearby\" so that, on average, adding a pickup/deliver order to a courier that's active inside that area is considered to be acceptable\n",
    " \n",
    " - This also reduces the penalty that a courier incurs if he/she must pickup/deliver orders sequentially, rather than concurrently.\n",
    "\n",
    "- Let's assume that each courier has a *delivery list*, which are the next orders he/she will fulfill and, when we `push` an order to a courier, it means that we will add that order to the end of his/her delivery list.\n",
    "\n",
    " - We can also `insert` an order into an arbitrary place in his/her list (e.g. for time-constrained orders that must be picked-up/delivered at a given time)\n",
    "\n",
    "- All other things being equal, we would rather assign a new order to an active courier, so as to avoid him/her becoming *inactive*.\n",
    "\n",
    "- We need to keep a pool of waiting couriers (for orders no active courier can take) but it must be as small as possible, because it costs money to keep them waiting and, while they are waiting, they don't generate any money for us.\n",
    "\n",
    " - in other words, we want to be able to deliver all orders using the smallest possible amount of couriers "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Version 1 (Blocking; sequential order processing)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "function: get_active_couriers_by_base_area(x)\n",
    "    \n",
    "  return all active couriers who, **by the end of their respective order lists**, will have x as base area,\n",
    "  with couriers with smallest order lists first    "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "function: get_adjacent_areas(x)\n",
    "\n",
    "  return areas which are adjacent to x"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "for each new order o:\n",
    "\n",
    "   for each area a: \n",
    "\n",
    "       if o is completely within area a:\n",
    "\n",
    "            \n",
    "\n",
    "          if o is NOT time-constrained:\n",
    "\n",
    "                couriers <- get_active_couriers_by_base_area(a)\n",
    "                                \n",
    "                if couriers is not empty:\n",
    "                    c <- couriers.get_first()\n",
    "                    push o to c\n",
    "                \n",
    "                else // no active couriers available in area a\n",
    "                \n",
    "                    as  <- get_adjacent_areas(a)\n",
    "                    couriers_in_adjacent_areas <- get_active_couriers_by_base_area(as)\n",
    "                    \n",
    "                    if couriers_in_adjacent_areas is not empty:\n",
    "                        c <- couriers_in_adjacent_areas.get_first()\n",
    "                        push o to c\n",
    "                    \n",
    "                    else // no available active couriers even in adjacent areas       \n",
    "                        c <- get_first_waiting_courier()\n",
    "                        push o to c\n",
    "\n",
    "            else // o IS time-constrained:\n",
    "                    \n",
    "                candidate_couriers <- get_active_couriers_by_base_area(a)        \n",
    "                         \n",
    "                if candidate_couriers is not empty         \n",
    "                         \n",
    "                    for each active courier c in candidate_couriers:\n",
    "\n",
    "                        if all orders after o's pickup time are NOT time-constrained \n",
    "                            AND the state of c's trunk supports the addition of a package as large as o:\n",
    "                                insert o in c's delivery list, after the first order that\n",
    "                                can be picked/up delivered before o's pickup time, given the time estimates\n",
    "                                and shift all other orders after that\n",
    "\n",
    "                else: // no candidate couriers in base area a\n",
    "\n",
    "                    as <- get_adjacent_areas(a)\n",
    "                    candidate_couriers <- get_active_couriers_by_base_area(as) \n",
    "                    \n",
    "\n",
    "                    if candidate_couriers is not empty         \n",
    "                         \n",
    "                        for each active courier c in candidate_couriers:\n",
    "\n",
    "                            if all orders after o's pickup time are NOT time-constrained \n",
    "                                AND the state of c's trunk supports the addition of a package as large as o:\n",
    "                                    insert o in c's delivery list, after the first order that\n",
    "                                    can be picked/up delivered before o's pickup time, given the time estimates\n",
    "                                    and shift all other orders after that\n",
    "\n",
    "                    else // no active couriers could be found, even in adjacent areas\n",
    "                        c <- get_first_waiting_courier()\n",
    "                        push o to c\n",
    "\n",
    "   else: // this order spans multiple areas\n",
    "\n",
    "          a <- o.pickup.get_area() \n",
    "          \n",
    "          if O is NOT time-constrained\n",
    "              couriers <- get_active_couriers_by_base_area(a)\n",
    "              \n",
    "              if couriers is not empty:\n",
    "                    c <- couriers.get_first()\n",
    "                    push o to c\n",
    "              \n",
    "              else // no active couriers available in area a\n",
    "                    as  <- get_adjacent_areas(a)\n",
    "                    couriers_in_adjacent_areas <- get_active_couriers_by_base_area(as)\n",
    "   \n",
    "                    if couriers_in_adjacent_areas is not empty:\n",
    "                        c <- couriers_in_adjacent_areas.get_first()\n",
    "                        push o to c \n",
    "                                              \n",
    "                    else // no available active couriers even in adjacent areas       \n",
    "                        c <- get_first_waiting_courier()\n",
    "                        push o to c\n",
    "                        \n",
    "\n",
    "          else: // order IS time-constrained\n",
    "                         \n",
    "                candidate_couriers <- get_active_couriers_by_base_area(a)        \n",
    "                         \n",
    "                if candidate_couriers is not empty         \n",
    "                         \n",
    "                    for each active courier c in candidate_couriers:\n",
    "\n",
    "                        if all orders after o's pickup time are NOT time-constrained \n",
    "                            AND the state of c's trunk supports the addition of a package as large as o:\n",
    "                                insert o in c's delivery list, after the first order that\n",
    "                                can be picked/up delivered before o's pickup time, given the time estimates\n",
    "                                and shift all other orders after that\n",
    "\n",
    "                else: // no candidate couriers in base area a\n",
    "\n",
    "                    as <- get_adjacent_areas(a)\n",
    "                    candidate_couriers <- get_active_couriers_by_base_area(as) \n",
    "                    \n",
    "\n",
    "                    if candidate_couriers is not empty         \n",
    "                         \n",
    "                        for each active courier c in candidate_couriers:\n",
    "\n",
    "                            if all orders after o's pickup time are NOT time-constrained \n",
    "                                AND the state of c's trunk supports the addition of a package as large as o:\n",
    "                                    insert o in c's delivery list, after the first order that\n",
    "                                    can be picked/up delivered before o's pickup time, given the time estimates\n",
    "                                    and shift all other orders after that\n",
    "\n",
    "                    else // no active couriers could be found, even in adjacent areas\n",
    "                        c <- get_first_waiting_courier()\n",
    "                        push o to c\n",
    "              \n",
    "\n",
    "\n",
    "NOTES:\n",
    "\n",
    "- if a courier delivers an order in area B, that area becomes his BASE area for the day (unless it's changed again)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "for each new order o:\n",
    "\n",
    "\n",
    "    a <- o.pickup.get_area()            \n",
    "\n",
    "    if o is NOT time-constrained:\n",
    "\n",
    "        couriers <- get_active_couriers_by_base_area(a)\n",
    "\n",
    "        if couriers is not empty:\n",
    "            c <- couriers.get_first()\n",
    "            push o to c\n",
    "\n",
    "        else // no active couriers available in area a, so we try in adjacent areas\n",
    "\n",
    "            as  <- get_adjacent_areas(a)\n",
    "            couriers_in_adjacent_areas <- get_active_couriers_by_base_area(as)\n",
    "\n",
    "            if couriers_in_adjacent_areas is not empty:\n",
    "                c <- couriers_in_adjacent_areas.get_first()\n",
    "                push o to c\n",
    "\n",
    "            else // no available active couriers even in adjacent areas       \n",
    "                c <- get_first_waiting_courier()\n",
    "                push o to c\n",
    "\n",
    "    else // o IS time-constrained:\n",
    "\n",
    "        candidate_couriers <- get_active_couriers_by_base_area(a)        \n",
    "\n",
    "        if candidate_couriers is not empty         \n",
    "\n",
    "            for each active courier c in candidate_couriers:\n",
    "\n",
    "                if all orders after o's pickup time are NOT time-constrained \n",
    "                    AND the state of c's trunk supports the addition of a package as large as o:\n",
    "                        insert o in c's delivery list, after the first order that\n",
    "                        can be picked/up delivered before o's pickup time, given the time estimates\n",
    "                        and shift all other orders after that\n",
    "\n",
    "        else // no active couriers available in area a, so we try in adjacent areas\n",
    "\n",
    "            as <- get_adjacent_areas(a)\n",
    "            candidate_couriers <- get_active_couriers_by_base_area(as) \n",
    "\n",
    "            if candidate_couriers is not empty         \n",
    "\n",
    "                for each active courier c in candidate_couriers:\n",
    "\n",
    "                    if all orders after o's pickup time are NOT time-constrained \n",
    "                        AND the state of c's trunk supports the addition of a package as large as o:\n",
    "                            insert o in c's delivery list, after the first order that\n",
    "                            can be picked/up delivered before o's pickup time, given the time estimates\n",
    "                            and shift all other orders after that\n",
    "\n",
    "            else // no active couriers could be found, even in adjacent areas\n",
    "                c <- get_first_waiting_courier()\n",
    "                push o to c\n",
    "\n",
    "NOTES:\n",
    "\n",
    "- if a courier delivers an order in area B, that area becomes his BASE area for the day (unless it's changed again)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Analysis\n",
    "\n",
    "- if too many couriers get too burdened by this algorithm, we can adjust the following:\n",
    "\n",
    " - increase the size of the areas which will probably cause larger delivery queues for each courier\n",
    " \n",
    " - decrease the size of the areas (smaller areas will reduce the coverage area for each courier but may increase the number of order that span multiple areas)\n",
    " \n",
    " - add couriers\n",
    " \n",
    "- in the worst case scenario, we have a time complexity of\n",
    "\n",
    "### Complexity\n",
    "\n",
    "- the space complexity is as follows:\n",
    "\n",
    " - a list of orders for each active courier - O(N)\n",
    " \n",
    " - a list of couriers - O(N)\n",
    "\n",
    "### Things that can go wrong\n",
    "\n",
    "- a courier may decide to leave with a non-empty delivery list, in which case we must re-assign those orders\n",
    "\n",
    " - we could just re-add those order into the stream, as if they were new orders\n",
    "\n",
    "- If we compare this algorithm to a processor that has to process tasks, each courier would be a processor with a **single-core and no multiprocessing capabilities**, i.e. it can't have two orders concurrently.\n",
    "\n",
    " - This means that each courier can't *interleave* orders (as a processor switches between processes that are doing slow tasks such as reading from disk) a courier will sit idle for a long time if we have a time-constrained order where the delivery time is hours or days after the pickup time.\n",
    " \n",
    " - One solution for this is, naturally, to allow each courier (core) to process multiple orders (processes) at the same time, keeping the packages (process context) in memory. We could use the same scheduling mechanisms a processor uses, and watch out for things like starvation.\n",
    "\n",
    "### Other thoughts\n",
    "\n",
    "- we could consider dynamic areas, instead of static ones (say a circle with radius d around the courier)\n",
    "\n",
    "- or we could choose better areas, after we collect some data on which areas have more orders\n",
    "\n",
    "- maybe we should calculate the best courier for a given order based upon where that courier will be after the delivery of the last order in his/her queue\n",
    "\n",
    "- Consider cases when it's best for the courier not to pickup/deliver orders sequentially\n",
    "\n",
    " - But pickup both orders and then deliver both of them (i.e. add some sort of *concurrency*)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Version 2\n",
    "\n",
    "After looking at a couple of websites and research articles, one comes to the conclusion that, since there is no  known way (other than brute forcing all possible paths) to obtain an exact answer for all but trivial problems, one can approach this in one of two ways (stimmt das?)\n",
    "\n",
    "[The vehicle routing problem: State of the art classification and review](http://www.sciencedirect.com/science/article/pii/S0360835215004775)\n",
    "\n",
    "[Vehicle routing problems with loading constraints: state-of-the-art and future directions](https://link.springer.com/content/pdf/10.1007%2Fs00291-014-0386-3.pdf)\n",
    "\n",
    "[The Vehicle Routing Problem: An overview of exact and approximate algorithms](https://pdfs.semanticscholar.org/bd68/0d5708297eb76513611919c1145694db77e4.pdf)\n",
    "\n",
    "[A Tabu Search Heuristic for the Vehicle Routing Problem](https://www.researchgate.net/profile/Alain_Hertz/publication/227446596_A_Tabu_Search_Heuristic_for_the_Vehicle_Routing_Problem/links/0a85e52e66756ebe17000000.pdf)\n",
    "\n",
    "[Google Optimization Tools](https://developers.google.com/optimization/routing/tsp/vehicle_routing)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Global TF Kernel (Python 3)",
   "language": "python",
   "name": "global-tf-python-3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
